import axios from "axios"
import { useRouter } from "vue-router"
import useMessage from "../hooks/useMessage"
const request = axios.create({
    header: {
        'Content-Type': "application/json;charset=utf-8"
    }
})
const url = {
    LOCAL: "http://localhost:8083/zhaomuapi",
    SERVER: "https://www.nanotus.cn/zhaomuapi"
}

request.defaults.baseURL = url.SERVER
request.interceptors.request.use(config => {
    const token = localStorage.getItem("token")
    if (token) {
        config.headers.authorization = token;
    }
    return config
})
request.interceptors.response.use(response => {
    const data = response.data
    const token = response.headers.authorization
    if (token) {
        localStorage.setItem("token", token)
    }
    if (data.code == 400) {
        localStorage.removeItem("token")
    }
    return Promise.resolve(response)
})
export const get = (url, params) => {
    return new Promise((resolve, reject) => {
        request.get(url, {
            params
        }).then(res => {
            resolve(res.data)
        }).catch(res => {
            reject(res.data)
        })
    })
}
export const post = (url, data, showToast = true) => {
    return new Promise((resolve, reject) => {
        request.post(url, data).then(res => {
            resolve(res.data)
            if (res.data.code == 200) {
                useMessage(res.data.message, "success")
            } else if (res.data.code == 500) {
                useMessage(res.data.message, "warning")
            }
        }).catch(res => {
            reject(res.data)
        })
    })
}